// ============================================================================
// 微博数据管理页面
// ============================================================================

import React, { useState, useEffect } from 'react'
import { dataService } from '../services/data-service'
import { useNotifications } from '../hooks/use-notifications'
import { logger } from '../utils/logger'
import WeiboContent from '../components/WeiboContent'

/**
 * 微博数据统计信息
 */
interface WeiboDataStats {
  total: number
  today: number
  thisWeek: number
  thisMonth: number
  totalUsers: number
  totalTasks: number
  avgInteractions: number
  topKeywords: Array<{ keyword: string; count: number }>
}

/**
 * 微博数据项
 */
interface WeiboDataItem {
  id: string
  weiboId: string
  text: string
  userId: string
  userNickname: string
  userAvatar?: string
  source?: string
  repostsCount: number
  commentsCount: number
  likesCount: number
  images?: string[]
  video?: any
  location?: string
  isRepost: boolean
  originalWeiboId?: string
  publishedAt: Date
  taskId?: string
  createdAt: Date
  updatedAt: Date
}

/**
 * 微博数据管理页面组件
 */
export const WeiboDataPage: React.FC = () => {
  const [stats, setStats] = useState<WeiboDataStats | null>(null)
  const [weiboData, setWeiboData] = useState<WeiboDataItem[]>([])
  const [loading, setLoading] = useState(true)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize] = useState(20)
  const [totalCount, setTotalCount] = useState(0)
  const [searchKeyword, setSearchKeyword] = useState('')
  const [filterType, setFilterType] = useState<'all' | 'original' | 'repost'>('all')
  const [sortBy, setSortBy] = useState<'createdAt' | 'publishedAt' | 'interactions'>('createdAt')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')
  const { showSuccess, showError } = useNotifications()

  // 加载数据
  useEffect(() => {
    loadData()
  }, [currentPage, searchKeyword, filterType, sortBy, sortOrder])

  /**
   * 加载所有数据
   */
  const loadData = async () => {
    try {
      setLoading(true)
      await Promise.all([
        loadStats(),
        loadWeiboData()
      ])
    } catch (error) {
      logger.error('加载数据失败', error)
      showError('加载数据失败', `${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  /**
   * 加载统计信息
   */
  const loadStats = async () => {
    try {
      const statsData = await dataService.getWeiboDataStats()
      setStats(statsData)
    } catch (error) {
      logger.error('加载统计信息失败', error)
      throw error
    }
  }

  /**
   * 加载微博数据列表
   */
  const loadWeiboData = async () => {
    try {
      const result = await dataService.getWeiboDataList({
        page: currentPage,
        pageSize,
        keyword: searchKeyword,
        filterType,
        sortBy,
        sortOrder
      })
      setWeiboData(result.data)
      setTotalCount(result.total)
    } catch (error) {
      logger.error('加载微博数据失败', error)
      throw error
    }
  }

  /**
   * 搜索处理
   */
  const handleSearch = (keyword: string) => {
    setSearchKeyword(keyword)
    setCurrentPage(1)
  }

  /**
   * 筛选处理
   */
  const handleFilter = (type: 'all' | 'original' | 'repost') => {
    setFilterType(type)
    setCurrentPage(1)
  }

  /**
   * 排序处理
   */
  const handleSort = (field: 'createdAt' | 'publishedAt' | 'interactions') => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
    } else {
      setSortBy(field)
      setSortOrder('desc')
    }
    setCurrentPage(1)
  }

  /**
   * 格式化数字
   */
  const formatNumber = (num: number): string => {
    if (num >= 10000) {
      return `${(num / 10000).toFixed(1)}万`
    }
    return num.toLocaleString()
  }

  /**
   * 格式化日期
   */
  const formatDate = (date: Date | string): string => {
    const d = new Date(date)
    return d.toLocaleString('zh-CN')
  }

  /**
   * 计算总页数
   */
  const totalPages = Math.ceil(totalCount / pageSize)

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-lg text-gray-600">加载中...</div>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">微博数据管理</h1>
        <div className="flex items-center space-x-4">
          <button
            onClick={loadData}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium"
          >
            刷新数据
          </button>
        </div>
      </div>

      {/* 统计卡片 */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-white p-6 rounded-lg border">
            <div className="text-3xl font-bold text-blue-600">
              {formatNumber(stats.total)}
            </div>
            <div className="text-sm text-gray-600">总微博数</div>
          </div>
          
          <div className="bg-white p-6 rounded-lg border">
            <div className="text-3xl font-bold text-green-600">
              {formatNumber(stats.today)}
            </div>
            <div className="text-sm text-gray-600">今日新增</div>
          </div>
          
          <div className="bg-white p-6 rounded-lg border">
            <div className="text-3xl font-bold text-purple-600">
              {formatNumber(stats.thisWeek)}
            </div>
            <div className="text-sm text-gray-600">本周新增</div>
          </div>
          
          <div className="bg-white p-6 rounded-lg border">
            <div className="text-3xl font-bold text-orange-600">
              {formatNumber(stats.thisMonth)}
            </div>
            <div className="text-sm text-gray-600">本月新增</div>
          </div>
        </div>
      )}

      {/* 详细统计信息 */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-white p-4 rounded-lg border">
            <div className="text-lg font-semibold text-gray-900 mb-2">用户统计</div>
            <div className="text-2xl font-bold text-indigo-600">
              {formatNumber(stats.totalUsers)}
            </div>
            <div className="text-sm text-gray-600">总用户数</div>
          </div>
          
          <div className="bg-white p-4 rounded-lg border">
            <div className="text-lg font-semibold text-gray-900 mb-2">任务统计</div>
            <div className="text-2xl font-bold text-teal-600">
              {formatNumber(stats.totalTasks)}
            </div>
            <div className="text-sm text-gray-600">关联任务数</div>
          </div>
          
          <div className="bg-white p-4 rounded-lg border">
            <div className="text-lg font-semibold text-gray-900 mb-2">平均互动</div>
            <div className="text-2xl font-bold text-pink-600">
              {formatNumber(stats.avgInteractions)}
            </div>
            <div className="text-sm text-gray-600">平均互动数</div>
          </div>
        </div>
      )}

      {/* 搜索和筛选 */}
      <div className="bg-white p-4 rounded-lg border">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
          {/* 搜索框 */}
          <div className="flex-1 max-w-md">
            <input
              type="text"
              placeholder="搜索微博内容..."
              value={searchKeyword}
              onChange={(e) => handleSearch(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* 筛选按钮 */}
          <div className="flex items-center space-x-2">
            <button
              onClick={() => handleFilter('all')}
              className={`px-3 py-2 text-sm rounded-lg ${
                filterType === 'all'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              全部
            </button>
            <button
              onClick={() => handleFilter('original')}
              className={`px-3 py-2 text-sm rounded-lg ${
                filterType === 'original'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              原创
            </button>
            <button
              onClick={() => handleFilter('repost')}
              className={`px-3 py-2 text-sm rounded-lg ${
                filterType === 'repost'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              转发
            </button>
          </div>
        </div>
      </div>

      {/* 微博数据列表 */}
      <div className="bg-white rounded-lg border">
        <div className="px-6 py-4 border-b">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-900">微博数据列表</h2>
            <div className="text-sm text-gray-500">
              共 {formatNumber(totalCount)} 条数据
            </div>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  用户信息
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  微博内容
                </th>
                <th
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('interactions')}
                >
                  互动数据 {sortBy === 'interactions' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('publishedAt')}
                >
                  发布时间 {sortBy === 'publishedAt' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('createdAt')}
                >
                  采集时间 {sortBy === 'createdAt' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {weiboData.length === 0 ? (
                <tr>
                  <td colSpan={5} className="px-6 py-8 text-center text-gray-500">
                    暂无数据
                  </td>
                </tr>
              ) : (
                weiboData.map((item) => (
                  <tr key={item.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4">
                      <div className="flex items-center">
                        {item.userAvatar && (
                          <img
                            className="h-10 w-10 rounded-full mr-3"
                            src={item.userAvatar}
                            alt={item.userNickname}
                          />
                        )}
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {item.userNickname}
                          </div>
                          <div className="text-sm text-gray-500">
                            ID: {item.userId}
                          </div>
                        </div>
                      </div>
                    </td>

                    <td className="px-6 py-4">
                      <div className="max-w-sm">
                        <WeiboContent
                          content={item.text}
                          maxLines={3}
                          className="text-sm"
                        />
                        <div className="flex items-center mt-2 space-x-2">
                          {item.isRepost && (
                            <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">
                              转发
                            </span>
                          )}
                          {item.images && item.images.length > 0 && (
                            <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">
                              📷 图片 {item.images.length}
                            </span>
                          )}
                          {item.video && (
                            <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-purple-100 text-purple-800">
                              🎥 视频
                            </span>
                          )}
                          {item.location && (
                            <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
                              📍 {item.location}
                            </span>
                          )}
                        </div>
                      </div>
                    </td>

                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900">
                        <div>转发: {formatNumber(item.repostsCount)}</div>
                        <div>评论: {formatNumber(item.commentsCount)}</div>
                        <div>点赞: {formatNumber(item.likesCount)}</div>
                      </div>
                    </td>

                    <td className="px-6 py-4 text-sm text-gray-900">
                      {formatDate(item.publishedAt)}
                    </td>

                    <td className="px-6 py-4 text-sm text-gray-900">
                      {formatDate(item.createdAt)}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* 分页 */}
        {totalPages > 1 && (
          <div className="px-6 py-4 border-t">
            <div className="flex items-center justify-between">
              <div className="text-sm text-gray-700">
                显示第 {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, totalCount)} 条，
                共 {totalCount} 条数据
              </div>

              <div className="flex items-center space-x-2">
                <button
                  onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                  disabled={currentPage === 1}
                  className="px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  上一页
                </button>

                <div className="flex items-center space-x-1">
                  {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                    const page = i + 1
                    return (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page)}
                        className={`px-3 py-2 text-sm rounded-lg ${
                          currentPage === page
                            ? 'bg-blue-600 text-white'
                            : 'border border-gray-300 hover:bg-gray-50'
                        }`}
                      >
                        {page}
                      </button>
                    )
                  })}
                </div>

                <button
                  onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                  disabled={currentPage === totalPages}
                  className="px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  下一页
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
